<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 商品分类
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-input v-model="query.title" placeholder="标题" class="handle-input mr10"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
            </div>
            <el-table
                    v-loading="loading"
                    :data="tableDataT"
                    border
                    class="table"
                    ref="multipleTable"
                    header-cell-class-name="table-header"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="id" label="ID" width="55" align="center"></el-table-column>
                <el-table-column prop="title" label="标题"></el-table-column>
                <el-table-column label="封面图" align="center">
                    <template slot-scope="scope">
                        <el-image
                                class="table-td-thumb"
                                :src="scope.row.itemLogo"
                                :preview-src-list="[scope.row.itemLogo]"
                        ></el-image>
                    </template>
                </el-table-column>
                <el-table-column prop="orderNum" label="排序"></el-table-column>
                <el-table-column prop="createTime" label="创建时间" width="180">
                    <template slot-scope="scope">
                        <span>{{ parseDateTime(scope.row.createTime) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="320" align="center">
                    <template slot-scope="scope">
                        <el-button
                                type="text"
                                icon="el-icon-edit"
                                @click="handleEdit(scope.$index, scope.row)"
                        >编辑</el-button>
                        <el-button
                                type="text"
                                icon="el-icon-edit"
                                @click="handleParamsEdit(scope.$index, scope.row)"
                        >规格</el-button>
                        <el-button
                                type="text"
                                icon="el-icon-delete"
                                class="red"
                                @click="handleDelete(scope.$index, scope.row)"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                        background
                        layout="total, prev, pager, next"
                        :current-page="query.current"
                        :page-size="query.size"
                        :total="pageTotal"
                        @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" :visible.sync="editVisible" width="50%">
            <el-form ref="form" :model="form" :rules="rules" label-width="70px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="标题" prop="title" >
                            <el-input v-model="form.title"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="分类" >
                            <el-select v-model="form.catId" placeholder="请选择">
                                <el-option
                                        v-for="item in catOptions"
                                        :key="item.id"
                                        :label="item.title"
                                        :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="封面图">
                    <el-upload
                            class="avatar-uploader"
                            ref="upload"
                            action=""
                            :http-request="fileUpload"
                            :show-file-list="false"
                            :before-upload="beforeAvatarUpload">
                        <img v-if="form.itemLogo" :src="form.itemLogo" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>

                <el-form-item label="轮播图">
                    <el-upload
                            ref="uploads"
                            action=""
                            :http-request="fileUploadI"
                            list-type="picture-card"
                            :file-list='form.imageArr'
                            :on-preview="handlePictureCardPreview"
                            :on-remove="handleRemove">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                </el-form-item>

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="现价" >
                            <el-input v-model="form.prePrice"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="原价" >
                            <el-input v-model="form.origPrice"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="是否上架" >
                            <el-radio-group v-model="form.status">
                                <el-radio label="0">上架</el-radio>
                                <el-radio label="1">下架</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="排序" >
                            <el-input v-model.number="form.orderNum"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="内容">
                    <editor-bar v-model="form.content" :isClear="form.isClear"></editor-bar>
                </el-form-item>

            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog :visible.sync="form.dialogVisible">
            <img width="100%" :src="form.dialogImageUrl" alt="">
        </el-dialog>

        <el-dialog title="编辑" :visible.sync="editVisibleParams" width="50%" >
            <el-form ref="form" :model="formParams" :rules="rules" label-width="70px">
                <el-form-item>
                    <div class="stand">
                        <ul>
                            <li class="attr" v-for="(item,index) in standData" :key="index">
                                <span @click="remove(index)">删除:</span>
                                <el-input style="width: auto;" class="title" v-model="item.title" placeholder="请输入属性">:</el-input>
                                <div class="putt" v-if="item.attrs.length" v-for="(subitem,i) in item.attrs" :key="i">
                                    <el-input style="width: auto;" v-model="subitem.attr" placeholder="请输入值"></el-input>
                                    <div class="close" @click="closeAtrr(index,i)">×</div>
                                </div>
                                <div class="append" @click="addAtrr(index)">+</div>
                            </li>
                        </ul>
                        <div class="add">
                            <el-button type="primary" @click="addStand">添加规格</el-button>
                            <el-button type="primary" @click="getTable">生成规格列表</el-button>
                            <el-button type="primary" @click="read">读取规格列表</el-button>
                        </div>
                    </div>
                    <div class="table">
                        <el-table  v-if="isTable"
                                   :data="tableData"
                                   border
                                   height="350"
                                   style="width: 90%">
                            <el-table-column
                                    prop="paramData"
                                    label="属性">
                            </el-table-column>
                            <el-table-column
                                    prop="price"
                                    label="价格"
                                    width="180">
                                <template scope="scope">
                                    <el-input size="small" v-model="scope.row.price"></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column
                                    prop="stock"
                                    label="库存"
                                    width="180">
                                <template scope="scope">
                                    <el-input size="small" v-model="scope.row.stock"></el-input>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisibleParams = false">取 消</el-button>
                <el-button type="primary" @click="saveEditParams">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import { shopItemPage,shopItemInfo,shopItemSave,shopItemUpdate,shopItemUpdateSpecs,shopItemDelete } from '../../../api/shop/shopItem';
    import { shopItemCatListSelect } from '../../../api/shop/shopItemCat';

    import { fileUpload } from '../../../api/uploadFile';
    import EditorBar from '../../../components/common/WangEditor'
    export default {
        name: 'shop-item-list',
        data() {
            return {
                // 遮罩层
                loading: true,
                query: {
                    jobName: '',
                    current: 1,
                    size: 10
                },
                editVisible:false,
                editVisibleParams:false,
                form:{
                    id:'',
                    title:'',
                    itemLogo:'',
                    image:'',
                    imageArr: [],
                    dialogImageUrl:'',
                    dialogVisible: false,
                    prePrice:0,
                    origPrice:0,
                    status:0,
                    isClear: false,
                    content:"",
                    catId:""
                },
                catOptions: [],
                formParams:{
                    id:'',
                    arr:[]
                },
                tableDataT: [],
                pageTotal: 0,
                tableData: [],
                input: '',
                isTable: false,
                standData: [],
                list: [],
                group: [],
                rules: {
                    title: [
                        { required: true, message: '请输入名称', trigger: 'blur' }
                    ],
                    orderNum: [
                        { required: true, message: '请输入排序', trigger: 'blur' },
                        { type: 'number', message: '排序必须为数字值'}
                    ]
                }
            };
        },
        components: { EditorBar },
        created() {
            shopItemCatListSelect({}).then(res => {
                this.catOptions = res.list;
                this.defaultform = JSON.parse(JSON.stringify(this.form));
            });
            this.getData();
        },
        destroyed() {
            this.defaultform = null;
        },
        methods: {
            getData() {
                this.loading = true;
                shopItemPage(this.query).then(res => {
                    this.loading = false;
                    this.tableDataT = res.data;
                    this.pageTotal = res.count;
                });
            },
            handleRemove(file, fileList) {
                this.form.imageArr = fileList;
            },
            handlePictureCardPreview(file) {
                this.form.dialogImageUrl = file.url;
                this.form.dialogVisible = true;
            },
            // 删除操作
            handleDelete(index, row) {
                // 二次确认删除
                this.$confirm('确定要删除吗？', '提示', {
                    type: 'warning'
                })
                    .then(() => {
                        shopItemDelete(row.id).then(res => {
                            if (res.code == 0) {
                                this.editVisible = false;
                                this.$message.success(`删除成功`);
                                this.getData();
                            } else {
                                this.$message.error(res.msg);
                                return false;
                            }
                        });
                    })
                    .catch(() => {});
            },
            handleAdd(){
                this.form = Object.assign({}, this.defaultform);
                this.editVisible = true;
                this.$nextTick(()=>{
                    this.$refs['form'].clearValidate();
                })
            },
            handleEdit(index, row) {
                this.form.id = row.id;
                this.form.title = row.title;
                this.form.catId = row.catId;
                this.form.status = row.status;
                this.form.itemLogo = row.itemLogo;
                this.form.prePrice = row.prePrice;
                this.form.origPrice = row.origPrice;
                this.form.orderNum = row.orderNum;
                // content内容需要查询
                shopItemInfo(row.id).then(res => {
                    if (res.code == 0) {
                        this.form.content = res.item.content
                        if (res.item.image) {
                            let imageArr = [];
                            res.item.image.split(",").forEach(item => {
                                imageArr.push({url:item})
                            });
                            this.form.imageArr = imageArr
                        } else {
                            this.form.imageArr = [];
                        }
                    } else {
                        this.$message.error(res.msg);
                        return false;
                    }
                });
                this.editVisible = true;
                this.$nextTick(()=>{
                    this.$refs['form'].clearValidate();
                })
            },
            handleParamsEdit(index, row) {
                this.isTable = true
                this.formParams.id = row.id;
                // 获取
                shopItemInfo(row.id).then(res => {
                    if (res.code == 0) {
                        let arr = [];
                        if (res.itemSpecsList) {
                            res.itemSpecsList.forEach(item => {
                                arr.push(item.paramData)
                            })
                            this.tableData = res.itemSpecsList
                        }
                        this.formParams.arr = arr
                        this.read();
                    } else {
                        this.$message.error(res.msg);
                        return false;
                    }
                });
                this.editVisibleParams = true;
            },
            // 保存编辑
            saveEdit() {
                this.$refs['form'].validate((valid) => {
                    if (!valid) {
                        console.log('error submit!!');
                        return false;
                    }
                    let imageArr = this.form.imageArr;
                    if (imageArr == null || imageArr.length <= 0) {
                        this.$message.error("请上传图片");
                        return false;
                    }
                    let images = [];
                    imageArr.forEach(item => {
                        images.push(item.url);
                    })
                    this.form.image = images.join(",");
                    if (this.form.id) {
                        shopItemUpdate(this.form).then(res => {
                            if (res.code == 0) {
                                this.editVisible = false;
                                this.$message.success(`修改成功`);
                                this.getData();
                            } else {
                                this.$message.error(res.msg);
                                return false;
                            }
                        });
                    } else {
                        shopItemSave(this.form).then(res => {
                            if (res.code == 0) {
                                this.editVisible = false;
                                this.$message.success(`修改成功`);
                                this.getData();
                            } else {
                                this.$message.error(res.msg);
                                return false;
                            }
                        });
                    }
                });
            },
            saveEditParams() {
                // 获取数据
                let id = this.formParams.id;
                // json是table数据
                let json = JSON.stringify(this.tableData);
                shopItemUpdateSpecs({id:id,itemSpecsJson:json}).then(res => {
                    if (res.code == 0) {
                        this.editVisibleParams = false;
                        this.$message.success(`修改成功`);
                        this.getData();
                    } else {
                        this.$message.error(res.msg);
                        return false;
                    }
                });
            },
            // 触发搜索按钮
            handleSearch() {
                this.$set(this.query, 'current', 1);
                this.getData();
            },
            // 分页导航
            handlePageChange(val) {
                this.$set(this.query, 'current', val);
                this.getData();
            },
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            },
            fileUpload(file){
                let _this = this;
                return fileUpload(file).then(res => {
                    // 多图片上传，结果data里面是一个array
                    // console.log(res.data[0]);
                    _this.form.itemLogo = res.data[0]
                    // _this.handleAvatarSuccess(res, file)
                    _this.$refs.upload.clearFiles();//清空
                });
            },
            fileUploadI(file){
                let _this = this;
                return fileUpload(file).then(res => {
                    // 多图片上传，结果data里面是一个array
                    // console.log(res.data[0]);
                    _this.form.imageArr.push({url:res.data[0]});
                    // _this.handleAvatarSuccess(res, file)
                    _this.$refs.uploads.clearFiles();//清空
                });
            },
            // 添加规格行
            addStand (i) {
                //  限制规格种类不超过4种
                if (this.standData.length>3) {
                    this.$message('不能超过四行')
                } else {
                    this.standData.push({title: '', attrs: []})
                }
            },
            // 添加规格表格
            getTable () {
                this.isTable = true
                this.tableData = []
                this.group = []
                this.list = []
                if (this.standData == null || this.standData.length == 0) {
                    return false;
                }
                const num = this.standData.length
                this.standData.forEach(item => {
                    this.list.push(item.attrs)
                });
                let arr = []
                let that = this
                function func(skuarr=[], i){
                    for (let j=0; j<that.list[i].length; j++) {
                        if (i<that.list.length-1) {
                            skuarr[i] = that.list[i][j].attr
                            func(skuarr, i+1)
                        } else {
                            arr.push([...skuarr,that.list[i][j].attr])
                        }
                    }
                    return arr
                }
                let newList = func([], 0)
                let b
                newList.forEach(item => {
                    b = ''
                    for (let i = 0; i < num; i++) {
                        let a = this.standData[i].title
                        a = a + ':' + item[i]
                        b = b + a + ';'
                    }
                    this.group.push(b)
                })
                let table = []
                for (let j = 0; j < this.group.length; j++) {
                    table.push({
                        paramData: this.group[j],
                        stock: 0,
                        price: 0
                    })
                }
                this.tableData = table
            },
            // 删除规格行
            remove (i) {
                this.standData.splice(i,1)
            },
            // 添加属性值
            addAtrr (i) {
                //  限制属性值不超过5个
                if (this.standData[i].attrs.length>4) {
                    this.$message('不能超过5个')
                } else {
                    // 存的时候是存的对象
                    this.standData[i].attrs.push({attr: ''})
                }
            },
            // 删除属性值
            closeAtrr (a, b) {
                //   console.log(a, b);
                this.standData[a].attrs.splice(b,1)
            },
            // 读取规格属性数组
            read () {
                // 如果后台返回的数据是这样的
                const arr = this.formParams.arr
                if (arr == null || arr.length <= 0) {
                    return false;
                }
                const a = arr[0].split(';')
                const num =a.length-1
                let ss = []
                for (let tt = 0; tt < num; tt++){
                    ss.push([])
                }
                arr.forEach(item => {
                    for (let tt = 0; tt < num; tt++){
                        ss[tt].push(item.split(';')[tt].split(':')[1])
                    }
                })
                ss = ss.map(item => {
                    return Array.from(new Set(item))
                })
                for (let s = 0; s < ss.length; s++) {
                    for (let t = 0; t < ss[s].length; t++) {
                        ss[s][t] = {attr:ss[s][t]}
                    }
                }
                this.standData =[];
                for (let i = 0; i < num; i++) {
                    this.standData.push({'title': a[i].split(':')[0],attrs: ss[i]})
                }
            }
        }
    };
</script>

<style scoped>
    .handle-box {
        margin-bottom: 20px;
    }
    .handle-input {
        width: 300px;
        display: inline-block;
    }
    .table {
        width: 100%;
        font-size: 14px;
    }
    .red {
        color: #ff0000;
    }
    .mr10 {
        margin-right: 10px;
    }
    .table-td-thumb {
        display: block;
        margin: auto;
        width: 40px;
        height: 40px;
    }
    .table,.stand {
        padding: 20px;
    }
    .table {
        height: 300px;
    }
    .add {
        margin-top: 20px;
    }
    .attr {
        margin-bottom: 10px;
    }
    .putt {
        display: inline-block;
        position: relative;
        margin-right: 10px;
    }
    .append {
        width: 40px;
        height: 40px;
        background-color: aqua;
        line-height: 40px;
        text-align: center;
        display: inline-block;
        font-size: 28px;
        cursor: pointer;
        vertical-align: middle;
    }
    .title {
        background-color: bisque;
        margin-right: 10px;
    }
    .close {
        position: absolute;
        width: 15px;
        height: 15px;
        background-color: burlywood;
        border-radius: 50%;
        line-height: 15px;
        text-align: center;
        right: -5px;
        top: -5px;
    }
    .avatar-uploader  {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        width: 148px;
        height: 148px;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader:hover {
        border-color: #409EFF;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 148px;
        height: 148px;
        line-height: 148px;
        text-align: center;
    }
    .avatar {
        width: 148px;
        height: 148px;
        display: block;
    }
</style>
